import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../../App.css'
import '../../Login/login.css';
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading } from "antd-mobile";
import { useDispatch, useSelector } from "react-redux";
import { WALLET_LIST_USER_STATE_REQ_FAIL, WALLET_LIST_USER_STATE_REQ_SUCCESS, getUserState, isProofBankAccount, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import { saveEvent } from "@/store/actions/saveEvent";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing } from "@/utils/loanStatus";
import AddFavorite from "@/components/AddFavorite";
import AddHomeEvent from "@/utils/addHomeEvent";
import { WALLET_LIST_REQ_FAIL, WALLET_LIST_REQ_SUCCESS, deleteWallet, getWalletList } from "@/store/actions/walletList";
import icon_close from "@/assets/icon_close.png"
import icon_wallet_add from '@/assets/icon_wallet_add.png'
import DeleteWalletDialog from "@/components/DeleteWalletDialog/DeleteWalletDialog";
import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
import SubmitWalletDialog from "@/components/SubmitWalletDialog/SubmitWalletDialog";

/**
 * 钱包列表页
 */
export default function WalletList() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //显示delete wallet弹框
    const [deleteWalletMaskVisible, setDeleteWalletMaskVisible] = useState(false);
    const [deleteWalletInfo, setDeleteWalletInfo] = useState({});

    //显示submit wallet弹框
    const [submitWalletMaskVisible, setSubmitWalletMaskVisible] = useState(false);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的用户状态信息
    const userStateInfo = useSelector(state => state.userState)

    //获取Redux Store中的状态信息
    const walletListInfo = useSelector(state => state.walletList)

    //获取Redux Store中的用户状态信息
    // const userNotExistInfo = useSelector(state => state.userNotExist)

    //查询用户流程状态
    const checkUserStateInfo = async () => {
        console.log("ProofWalletList-checkUserStateInfo: ");

        //获取用户状态
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserState(PageTag.PROOF_MOBILE)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //查询用户钱包列表
    const checkWalletListInfo = async () => {
        console.log("ProofWalletList-checkWalletListInfo: ");

        //获取用户状态
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getWalletList(PageTag.PROOF_WALLET_LIST)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //绑定钱包
    const doDeleteWallet = async (ids) => {
        try {

            //判断是否可以提交
            if (ids.length === 0) {
                return
            }

            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = deleteWallet(ids, onDeleteWalletCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //绑定钱包返回
    const onDeleteWalletCallback = (success) => {
        //显示loading
        setMaskVisible(false)

        if (success) {
            //查询钱包列表
            checkWalletListInfo()
        }
    }

    //点击返回
    const onHandleNavGoBack = () => {
        console.log("go back")
        history.goBack()
    }

    // 点击删除监听
    const onHandleWalletDelete = (index) => {
        if (walletListInfo.list && walletListInfo.list.length > index) {
            const item = walletListInfo.list[index]
            setDeleteWalletInfo({ ...item })
            setDeleteWalletMaskVisible(true)
        }
    }

    // 点击确定删除监听
    const onHandleWalletDeleteConfirm = (walletId) => {
        //删除钱包接口
        doDeleteWallet(walletId)
    }

    // 点击确定删除监听
    const onHandleWalletDeleteCancel = () => {
        setDeleteWalletMaskVisible(false)
        setDeleteWalletInfo({})
    }

    // 点击添加卡监听
    const onHandleWalletAdd = () => {
        //跳转wave
        history.replace('/proofwalletwavebind')
    }

    // 点击保存绑卡状态监听
    const onHandleWalletSave = () => {
        setSubmitWalletMaskVisible(true)
    }

    // 点击确定提交监听
    const onHandleWalletSubmitConfirm = () => {
        setSubmitWalletMaskVisible(false)
        //调用 绑卡状态保存接口
    }

    // 点击确定提交监听
    const onHandleWalletSubmitCancel = () => {
        setSubmitWalletMaskVisible(false)
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //启动时请求首页额度
    useEffect(() => {
        //获取用户状态
        //checkUserStateInfo()

        //获取用户银行卡列表
        //checkWalletListInfo()

        //打点
        doHitEvent("PROOF_WALLET_LIST_START")

        return () => {
            //打点
            doHitEvent("PROOF_WALLET_LIST_END")
        }
    }, [])

    // 查询用户流程状态返回监听
    useEffect(() => {
        try {
            console.log("ProofWalletList-查询用户流程状态返回监听")
            console.log(userStateInfo)

            if (userStateInfo.status === WALLET_LIST_USER_STATE_REQ_SUCCESS) {
                //隐藏loading
                setMaskVisible(false)

                //是否为审核中
                const isHomeReviewing = isLoanReviewing(userStateInfo.applyStatus)
                //是否为拒绝
                const isHomeReject = isLoanReject(userStateInfo.applyStatus, userStateInfo.orderStatus)
                //是否为放款中
                const isHomeLoaning = isLoanLoaning(userStateInfo.orderStatus)
                //是否为待还款
                const isHomeRepay = isLoanRepayNow(userStateInfo.orderStatus)
                //是否为待进件
                const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
                console.log("Launch-isHomeReviewing: " + isHomeReviewing)
                console.log("Launch-isHomeReject: " + isHomeReject)
                console.log("Launch-isHomeLoaning: " + isHomeLoaning)
                console.log("Launch-isHomeRepay: " + isHomeRepay)
                console.log("Launch-isHomeNotLoan: " + isHomeNotLoan)

                //跳转状态页
                if (isHomeReviewing) {
                    history.replace('/review')
                    return

                } else if (isHomeReject) {
                    history.replace('/reject')
                    return

                } else if (isHomeLoaning) {
                    history.replace('/loaning')
                    return

                } else if (isHomeRepay) {
                    history.replace('/repay')
                    return
                }

                //判断下是否已经做完所有认证
                if (userStateInfo.isProofFinish === true) {
                    //跳转申请页
                    history.replace('/apply')
                    return
                }

                //是否为常用app认证
                if (isProofFrequentlyUsedApps(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/prooffrequentlyapps')
                    return
                }

                //是否为人脸认证
                if (isProofFace(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proofface')
                    return
                }

                //是否为号码认证
                if (isProofMobile(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proofmobile')
                    return
                }

                //是否为钱包认证
                if (!isProofBankAccount(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proof')
                }

            } else if (userStateInfo.status === WALLET_LIST_USER_STATE_REQ_FAIL) {
                //隐藏loading
                setMaskVisible(false)
            }

        } catch (e) {
            console.log(e)
        }
    }, [userStateInfo])


    //监听用户是否存在
    // useEffect(() => {
    //     if (userNotExistInfo.notExist === true) {
    //         //history.replace('/login')
    //         history.replace('/loginfb')
    //     }
    // }, [userNotExistInfo])


    //监听钱包列表接口返回
    useEffect(() => {
        console.log("ProofWalletList-监听钱包列表接口返回")
        console.log(walletListInfo)
        //获取短信发送成功返回
        if (walletListInfo.status === WALLET_LIST_REQ_SUCCESS) {
            //关闭loading
            setMaskVisible(false)

        } else if (walletListInfo.status === WALLET_LIST_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [walletListInfo])

    return (
        <div className="proofRoot">
            {/* <NavBar onBack={() => { history.goBack() }} style={{ 'width': '100%', 'backgroundColor': 'white' }}>Proof</NavBar> */}
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="proofContent">
                {/* 已绑卡列表 */}
                {walletListInfo.list && userStateInfo.list.map((value, index) => {
                    return (
                        <div className="proofItemList" key={index}>
                            <div className="proofItemWalletContent">
                                <img className="proofItemWalletLogo" src={value.walletLogo} alt="" />
                                <span className="proofItemWalletType">{value.type}</span>
                                <img className="proofItemWalletDelete" src={icon_close} alt="" onClick={() => { onHandleWalletDelete(index) }} />
                            </div>
                        </div>
                    )
                })}

                {/* 新增绑卡 */}
                <div className="proofItemList proofMarginTop24Px" onClick={onHandleWalletAdd}>
                    <div className="proofItemWalletAddContent">
                        <img className="proofItemWalletAddLogo" src={icon_wallet_add} alt="" />
                        <span className="proofItemWalletAddTitle">Ajouter</span>
                    </div>
                </div>
            </div>

            <div className="proofOtpTips">Veuillez ajouter votre portefeuille électronique mobile pour recevoir votre prêt</div>
            <div className="proofOtpTips">Afin de vous assurer que vous pouvez recevoir le prêt, veuillez ajouter autant de portefeuilles mobiles que possible pour éviter le problème de la limite affectant le transfert du prêt vers vous.</div>

            {/* 点击确定 */}
            <div className="proofApplyBtn" onClick={onHandleWalletSave}>
                <div className="mainButtonGradient">SUIVANT</div>
            </div>

            {/* add home gif dialog */}
            <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} />

            {/* delete wallet dialog */}
            <DeleteWalletDialog visible={deleteWalletMaskVisible} onConfirm={onHandleWalletDeleteConfirm} onClose={onHandleWalletDeleteCancel} walletInfo={deleteWalletInfo} />

            {/* submit wallet dialog */}
            <SubmitWalletDialog visible={submitWalletMaskVisible} onConfirm={onHandleWalletSubmitConfirm} onClose={onHandleWalletSubmitCancel} walletList={walletListInfo.list} />

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}